#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/14 1:01
# @Author : cjw
from datetime import datetime, timedelta

import jwt

from app.core.config import settings

access_token_jwt_subject = 'access'  # 访问令牌主题


def create_access_token(*, data: dict, expires_delta: timedelta = None) -> bytes:
    """
    生成令牌
    :param data: 令牌携带的数据
    :param expires_delta: 令牌过期时间
    :return:
    """
    to_encode = data.copy()  # 浅拷贝

    # 令牌过期时间，默认15分钟
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire, "sub": access_token_jwt_subject})
    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
    return encoded_jwt
